# -*- coding:utf-8 -*-
# @Time : 2020/7/14 8:18
# @Author : Administrator
# @File : cart.py
# @Software: PyCharm
# @Motto: good good study,day day up

from decimal import Decimal
from django.conf import settings
from shop.models import Product
from coupons.models import Coupon


class Cart:
    """初始化购物车对象"""

    def __init__(self, request):
        self.session = request.session
        cart = self.session.get(settings.CART_SESSION_ID)
        if not cart:
            # 向session中存入空白购物车数据
            cart = self.session[settings.CART_SESSION_ID] = {}
        self.cart = cart
        self.coupon_id = self.session.get('coupon_id')

    def __iter__(self):
        """遍历所有购物车中的商品并从数据库中取得商品对象"""
        product_ids = self.cart.keys()
        # 获取购特车内所有商品对象
        products = Product.objects.filter(id__in=product_ids)
        cart = self.cart.copy()
        for product in products:
            cart[str(product.id)]['product'] = product

        for item in cart.values():
            item['price'] = Decimal(item['price'])
            item['total_price'] = item['price'] * item['quantity']
            yield item

    def __len__(self):
        """购特车一共有几种商品"""
        return sum(item['quantity'] for item in self.cart.values())

    def add(self, product, quantity=1, update_quantity=False):
        """向购物车中增加商品或者更新购物车中的数量"""
        product_id = str(product.id)
        if product_id not in self.cart:
            self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}
        if update_quantity:
            self.cart[product_id]['quantity'] = quantity
        else:
            self.cart[product_id]['quantity'] += quantity
        self.save()

    def save(self):
        # 设置session.modified的值为True，中间件在看到这个属性的时候，就会保存session
        self.session.modified = True

    def remove(self, product):
        """从购物车中删除商品"""
        product_id = str(product.id)
        if product_id in self.cart:
            del self.cart[product_id]
            self.save()

    def get_total_price(self):
        return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())

    # 如果购物车包含一个coupon_id属性，会返回该id对应的Coupon对象
    @property
    def coupon(self):
        if self.coupon_id:
            return Coupon.objects.get(id=self.coupon_id)
        return None

    # 如果包含优惠码id，计算折扣价格，否则返回0
    def get_discount(self):
        if self.coupon:
            return (self.coupon.discount / Decimal('100')) * self.get_total_price()
        return Decimal('0')

    # 返回总价减去折扣价之后的折扣后价格
    def get_total_price_after_discount(self):
        return self.get_total_price() - self.get_discount()
